/*
 * Copyright (c) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import commonEventManager from '@ohos.commonEventManager'
import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from '@ohos/hypium'

export default function ActsSubscriberTestOrder() {
describe('SUB_NOTIFICATION_CES_SUBSCRIBER_ORDER_TEST', async function () {
    const TAG = 'SUB_NOTIFICATION_CES_SUBSCRIBER_ORDER_TEST ===>';
    console.log(`${TAG} SUB_NOTIFICATION_CES_SUBSCRIBER_ORDER_TEST START`);
    let subscribersAll = [];

    function publishCallback(err) {
        if (err) {
            console.error(`${TAG} publish failed, code is ${err.code}, \
                message is ${err.message}.`);
        } else {
            console.log(`${TAG} publish succeeded.`);
        }
    }

    function sleep(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }

    async function createSubscriberAndSubscribe(subscriberOption, subscribeCallback) {
        try {
            let subscriber = await commonEventManager.createSubscriber(subscriberOption);
            try {
                commonEventManager.subscribe(subscriber, subscribeCallback);
                console.log(`${TAG} subscribe succeeded`);
            } catch (err) {
                console.error(`${TAG} subscribe failed, code is ${err.code}, \
                    message is ${err.message}.`);
                expect(false).assertTrue();
            };
            subscribersAll.push(subscriber);
            await sleep(200);
            return subscriber;
        } catch (err) {
            console.error(`${TAG} create subscriber failed, code is ${err.code}, \
                message is ${err.message}.`);
            expect(false).assertTrue();
        };
    }

    /*
    * @tc.number    : SUB_NOTIFICATION_CES_SUBSCRIBER_ORDER_TEST_0100
    * @tc.name      : verify subscribe and publish : Check subscribe event and publish common event
    * @tc.desc      : Check the subscriber can receive event "publish_event0100" type of the interface
    */
    it('SUB_NOTIFICATION_CES_SUBSCRIBER_ORDER_TEST_0100', 0, async function (done) {
        console.log(`${TAG} SUB_NOTIFICATION_CES_SUBSCRIBER_ORDER_TEST_0100 START`);
        const EVENT_NAME = 'publish_event0100';
        const EVENT_CODE = 1;
        const EVENT_DATA = 'publish_event0100 data';
        let eventPublishData = {
            code: EVENT_CODE,
            data: EVENT_DATA
        };

        let subscriberOption = {
            events: [EVENT_NAME]
        };
        let subscriber = await createSubscriberAndSubscribe(subscriberOption,
            (err, data) => {
                if (err) {
                    console.log(`${TAG} subscriber callback failed, code is ${err.code}, \
                        message is ${err.message}.`);
                    expect(false).assertTrue();
                } else {
                    console.log(`${TAG} subscriber callback successed.`);
                    expect(data.event).assertEqual(EVENT_NAME);
                    expect(data.code).assertEqual(EVENT_CODE);
                    expect(data.data).assertEqual(EVENT_DATA);
                    console.log(`${TAG} SUB_NOTIFICATION_CES_SUBSCRIBER_ORDER_TEST_0100 END`);
                    done();
                }
            }
        );

        commonEventManager.publish(EVENT_NAME, eventPublishData, publishCallback);
        await sleep(200);
    });

    /*
     * @tc.number    : SUB_NOTIFICATION_CES_SUBSCRIBER_ORDER_TEST_0200
     * @tc.name      : verify subscribe and unsubscribe
     * @tc.desc      : Check the subscriber can receive event "publish_event0200" and can not receive event after unsubscribe
     */
    it ('SUB_NOTIFICATION_CES_SUBSCRIBER_ORDER_TEST_0200', 0, async function (done) {
        console.log(`${TAG} SUB_NOTIFICATION_CES_SUBSCRIBER_ORDER_TEST_0200 START`)
        const EVENT_NAME = 'publish_event0200';
        const EVENT_CODE = 2;
        const EVENT_DATA = 'publish_event0200 data';
        let eventPublishData = {
            code: EVENT_CODE,
            data: EVENT_DATA
        };

        let eventReceived = [];
        let subscriberOption = {
            events: [EVENT_NAME]
        };
        let subscriber = await createSubscriberAndSubscribe(subscriberOption,
            (err, data) => {
                if (err) {
                    console.error(`${TAG} subscriber callback failed, code is ${err.code}, \
                        message is ${err.message}.`);
                    expect(false).assertTrue();
                } else {
                    console.log(`${TAG} subscriber callback successed.`);
                    expect(data.event).assertEqual(EVENT_NAME);
                    eventReceived.push(0);
                }
            }
        );

        expect(eventReceived.length).assertEqual(0);
        commonEventManager.publish(EVENT_NAME, eventPublishData, publishCallback);
        await sleep(200);
        expect(eventReceived.length).assertEqual(1);
        commonEventManager.publish(EVENT_NAME, eventPublishData, publishCallback);
        await sleep(200);
        expect(eventReceived.length).assertEqual(2);

        try {
            commonEventManager.unsubscribe(subscriber, err => {
                if (err) {
                    console.error(`${TAG} unsubscribe failed, code is ${err.code}, message is ${err.message}`);
                    subscribersAll = subscribersAll.filter( subscriber_ => {
                        subscriber_ !== subscriber;
                    });
                    expect(false).assertTrue();
                } else {
                    console.log(`${TAG} unsubscribe`);
                }
            });
        } catch (err) {
            console.error(`${TAG} unsubscribe failed, code is ${err.code}, message is ${err.message}`);
            expect(false).assertTrue();
        };
        await sleep(200);
        commonEventManager.publish(EVENT_NAME, eventPublishData, publishCallback);
        await sleep(200);
        expect(eventReceived.length).assertEqual(2);
        commonEventManager.publish(EVENT_NAME, eventPublishData, publishCallback);
        await sleep(200);
        expect(eventReceived.length).assertEqual(2);

        console.log(`${TAG} SUB_NOTIFICATION_CES_SUBSCRIBER_ORDER_TEST_0200 END`);
        done();
    });

    /*
     * @tc.number    : SUB_NOTIFICATION_CES_SUBSCRIBER_ORDER_TEST_0300
     * @tc.name      : verify multiple subscribers subscribe
     * @tc.desc      : Check the subscribers can receive event "publish_event0300"
     */
    it ('SUB_NOTIFICATION_CES_SUBSCRIBER_ORDER_TEST_0300', 0, async function (done) {
        console.log(`${TAG} SUB_NOTIFICATION_CES_SUBSCRIBER_ORDER_TEST_0300 START`)
        const EVENT_NAME = 'publish_event0300';
        const EVENT_CODE = 3;
        const EVENT_DATA = 'publish_event0300 data';
        let eventPublishData = {
            code: EVENT_CODE,
            data: EVENT_DATA
        };
        const MAX_SUBSCRIBERS_NUM = 5;
        let subscribers = [];
        let subscribersReceiveEvent = [];

        for (let sid = 0; sid < MAX_SUBSCRIBERS_NUM; ++sid) {
            let subscriberOption = {
                events: [EVENT_NAME]
            };
            let subscriber = await createSubscriberAndSubscribe(subscriberOption,
                (err, data) => {
                    if (err) {
                        console.error(`${TAG} subscriber callback failed, code is ${err.code}, \
                            message is ${err.message}.`);
                        expect(false).assertTrue();
                    } else {
                        console.log(`${TAG} subscriber ${sid} callback successed.`);
                        expect(data.event).assertEqual(EVENT_NAME);
                        subscribersReceiveEvent.push(sid);
                    }
                }
            );
            subscribers.push(subscriber);
        }

        expect(subscribersReceiveEvent.length).assertEqual(0);
        commonEventManager.publish(EVENT_NAME, eventPublishData, publishCallback);
        await sleep(200);

        for (let sid = 0; sid < MAX_SUBSCRIBERS_NUM; ++sid) {
            if (!subscribersReceiveEvent.includes(sid)) {
                expect(false).assertTrue();
            }
        }
        console.log(`${TAG} SUB_NOTIFICATION_CES_SUBSCRIBER_ORDER_TEST_0300 END`);
        done();
    });

    /*
     * @tc.number    : SUB_NOTIFICATION_CES_SUBSCRIBER_ORDER_TEST_0400
     * @tc.name      : verify multiple subscribers with different priority subscribe an ordered event
     * @tc.desc      : Check the subscribers can receive event "publish_event0400" by priority order
     */
    it ('SUB_NOTIFICATION_CES_SUBSCRIBER_ORDER_TEST_0400', 0, async function (done) {
        console.log(`${TAG} SUB_NOTIFICATION_CES_SUBSCRIBER_ORDER_TEST_0400 START`)
        const EVENT_NAME = 'publish_event0400';
        const EVENT_CODE = 4;
        const EVENT_DATA = 'publish_event0400 data';
        let eventPublishData = {
            code: EVENT_CODE,
            data: EVENT_DATA,
            isOrdered: true
        };
        let subscriberInfos = [
            {id: 0, priority: 5},
            {id: 1, priority: 1},
            {id: 2, priority: 3},
            {id: 3, priority: 6},
            {id: 4, priority: 8},
            {id: 5, priority: 7}
        ];
        let subscribers = [];
        let subscribersReceiveEvent = [];

        for (let sinfo of subscriberInfos) {
            let subscriberOption = {
                events: [EVENT_NAME],
                priority: sinfo.priority
            };
            let subscriber = await createSubscriberAndSubscribe(subscriberOption,
                (err, data) => {
                    if (err) {
                        console.error(`${TAG} subscriber callback failed, code is ${err.code}, \
                            message is ${err.message}.`);
                        expect(false).assertTrue();
                    } else {
                        console.log(`${TAG} subscriber ${sinfo.id} callback successed.`);
                        expect(data.event).assertEqual(EVENT_NAME);
                        subscribersReceiveEvent.push(sinfo.id);
                    }
                }
            );
            subscribers.push(subscriber);
        }

        expect(subscribersReceiveEvent.length).assertEqual(0);
        commonEventManager.publish(EVENT_NAME, eventPublishData, publishCallback);
        await sleep(500);

        subscriberInfos.sort((a, b) => {
            return - (a.priority - b.priority);
        });
        console.debug(`${TAG} subscribersReceiveEvent ${JSON.stringify(subscribersReceiveEvent)}`);
        console.debug(`${TAG} subscriberInfos ${JSON.stringify(subscriberInfos)}`);
        expect(subscribersReceiveEvent.length).assertEqual(subscriberInfos.length);
        for (let i = 0; i < subscriberInfos.length; ++i) {
            expect(subscriberInfos[i].id === subscribersReceiveEvent[i]).assertTrue();
        }
        console.log(`${TAG} SUB_NOTIFICATION_CES_SUBSCRIBER_ORDER_TEST_0400 END`);
        done();
    });

    afterAll(async () => {
        for (let subscriber of subscribersAll) {
            commonEventManager.unsubscribe(subscriber, (err) => {
                if (err) {
                  console.error(`${TAG} Release subscribers failed, code is ${err.code}, \
                        message is ${err.message}.`);
                } else {
                  console.info(`${TAG} Release subscriber succeeded. `);
                }
            });
        }
    });

    console.log(`${TAG} SUB_NOTIFICATION_CES_SUBSCRIBER_ORDER_TEST END`);
});
};
